﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using GhostGame.DataObjects;

namespace GhostGame
{
    public class Global : System.Web.HttpApplication
    {

        void Application_Start(object sender, EventArgs e)
        {
            GameContainer.Users.Add(new User());
            // 在应用程序启动时运行的代码

        }

        void Application_End(object sender, EventArgs e)
        {
            //  在应用程序关闭时运行的代码

        }

        void Application_Error(object sender, EventArgs e)
        {
            // 在出现未处理的错误时运行的代码

        }

        void Session_Start(object sender, EventArgs e)
        {
            lock (GameContainer.Users)
            {
                User newUser = new User();
                GameContainer.Users.Add(newUser);
                newUser.ID = GameContainer.Users.Max(u => u.ID) + 1;
                newUser.Name = "新玩家";
                newUser.Died = false;
                newUser.IsGhost = false;
                this.Session["UserID"] = newUser.ID;
            }
        }

        void Session_End(object sender, EventArgs e)
        {
            User leftUser = GameContainer.Users.First(u => u.ID == (int)this.Session["UserID"]);
            GameContainer.Users.Remove(leftUser);
            DataObjects.GhostRoom room = GameContainer.Rooms.FirstOrDefault(r => r.Holder.ID == leftUser.ID);
            if (room != default(DataObjects.GhostRoom))
            {
                room.ClearRoom();
                GameContainer.Rooms.Remove(room);
            }
            room = GameContainer.Rooms.FirstOrDefault(r => r.Members.Select(u => u.ID).Contains(leftUser.ID));
            if (room != default(DataObjects.GhostRoom))
            {
                room.RemoveMember(leftUser.ID);
            }
        }

    }
}
